# -*- coding:utf-8 -*-
'''eof
name:申请人近半年内未结清业务逾期次数校验
code:Ind_UnpaidOverdueCnt_6monCheck
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

'''
贷款明细信息 ICRLoanInfo002*Loan
24个月还款状态 Latest24State
账户状态  State


贷记卡明细信息 ICRLoancardInfo002*Card
24个月还款状态 Latest24State
账户状态  State


准贷记卡明细信息  ICRStdLoancardInfo002*Std
24个月还款状态 Latest24State
账户状态  State




1.统计最近半年内未结清贷款的逾期记录数：
（1）截取每笔“账户状态”= “未结清”的贷款的“24个月还款状态”字段从右往左数的6位字符，统计这6位中的数字个数作为单笔未结清贷款最近半年内的逾期记录数；
（2）加总该客户所有未结清贷款的最近半年内的逾期记录数as factor1；
2.统计最近半年内未销户贷记卡的逾期记录数：
（1）截取每笔“账户状态”= “未销户”的贷记卡的“24个月还款状态”字段从右往左数的6位字符，统计这6位中的数字个数作为单笔未销户贷记卡最近半年内的逾期记录数；
（2）加总该客户所有未销户贷记卡最近半年内的逾期记录数as factor2；
3.统计最近半年内未销户准贷记卡的逾期记录数：
（1）截取每笔“账户状态”= “未销户”的准贷记卡的“24个月还款状态”字段从右往左数的6位字符，统计这6位中的数字个数作为单笔未销户准贷记卡最近半年内的逾期记录数；
（2）加总该客户所有未销户准贷记卡最近半年内的逾期记录数as factor3；
4.Factor = sum(factor1,factor2,factor3)
'''

import sys
import json

reload(sys)
sys.setdefaultencoding('utf-8')


##统计“最近24个月”还款状态中最近半年数字(不包括0,8,9)的个数
# 若“最近24个月”长度不为24，则返回空
# 若“最近24个月”最近半年不存在数字“1-7”，则返回0

def count_int(str_value, type):
    count = 0
    non_num = [u'1', u'2', u'3', u'4', u'5', u'6', u'7']
    znon_num = [u'3', u'4', u'5', u'6', u'7']
    non_type = ['card', 'loan']
    if len(str_value) == 24:
        half = str_value[-6:]
        if type in non_type:
            for i in half:
                if i in non_num:
                    count += 1
        if type == "std_card":
            for i in half:
                if i in znon_num:
                    count += 1
    else:
        return None
    return count


def Ind_UnpaidOverdueCnt_6monCheck():
    try:
        null_type_list = ['', None, 'null', '/', 'Null', 'NULL', '--', '-']
        if IC in null_type_list:
            return u'缺失值'
        if len(IC) == 0:
            return u'缺失值'
        icr = json.loads(IC[0]["icr"])
        if icr in null_type_list:
            return u'缺失值'
        if len(icr) == 0:
            return u'缺失值'
        # 贷款信息
        loan_nostate_type = [u'正常', u'逾期', u'呆账']
        loan_yesstate_type = [u'结清', u'转出']
        count_loan = []
        if icr.has_key('ICRLoanInfo002*Loan') and len(icr['ICRLoanInfo002*Loan']) >= 1:
            for i in icr['ICRLoanInfo002*Loan']:
                if i.has_key('State') and i.has_key('Latest24State'):
                    if i['State'] in loan_nostate_type:
                        count_loan.append(count_int(i['Latest24State'],'loan'))
                    elif i['State'] in loan_yesstate_type:
                        count_loan.append(int(0))
                    else:
                        count_loan.append(None)
                else:
                    count_loan.append(None)
        else:
            count_loan.append(None)

        # 加总贷款逾期记录
        count_loan1 = filter(lambda x: x is not None, count_loan)
        count_overloan = sum(count_loan1) if len(count_loan1) != 0 else None

        # 贷记卡信息
        card_nostate_type = [u'正常', u'冻结', u'呆账', u'止付']
        loan_yesstate_type = [u'销户', u'未激活']
        count_card = []
        if icr.has_key('ICRLoancardInfo002*Card') and len(icr['ICRLoancardInfo002*Card']) >= 1:
            for i in icr['ICRLoancardInfo002*Card']:
                if i.has_key('State') and i.has_key('Latest24State'):
                    if i['State'] in card_nostate_type:
                        count_card.append(count_int(i['Latest24State'],'card'))
                    elif i['State'] in loan_yesstate_type:
                        count_card.append(int(0))
                    else:
                        count_card.append(None)
                else:
                    count_card.append(None)
        else:
            count_card.append(None)

        # 加总贷记卡逾期记录
        count_card1 = filter(lambda x: x is not None, count_card)
        count_overcard = sum(count_card1) if len(count_card1) != 0 else None

        # 准贷记卡信息
        card_nostate_type = [u'正常', u'冻结', u'呆账', u'止付']
        loan_yesstate_type = [u'销户', u'未激活']
        count_std = []
        if icr.has_key('ICRStdLoancardInfo002*Std') and len(icr['ICRStdLoancardInfo002*Std']) >= 1:
            for i in icr['ICRStdLoancardInfo002*Std']:
                if i.has_key('State') and i.has_key('Latest24State'):
                    if i['State'] in card_nostate_type:
                        count_std.append(count_int(i['Latest24State'],'std_card'))
                    elif i['State'] in loan_yesstate_type:
                        count_std.append(int(0))
                    else:
                        count_std.append(None)
                else:
                    count_card.append(None)
        else:
            count_std.append(None)

        # 加总准贷记卡逾期记录
        count_std1 = filter(lambda x: x is not None, count_std)
        count_overstd = sum(count_std1) if len(count_std1) != 0 else None
        # 指标值取三个值的和,若均为空则返回缺失值
        total_overnum = [count_overloan, count_overcard, count_overstd]
        overnum = filter(lambda x: x is not None, total_overnum)
        return sum(overnum) if len(overnum) != 0 else u'缺失值'
    except:
        return u'缺失值'
    

result = Ind_UnpaidOverdueCnt_6monCheck()